package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.enums.OrderModuleEnum;
import com.example.pojo.FastgptVO;
import com.example.service.OrderService;
import com.example.service.ROVService;
import com.example.util.JsonUtil;
import com.example.util.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private AccessToFastGpt fastgpt;

    @Resource
    private ROVService rovService;

    @Value("${fastgpt.key.allorder}")
    private String FAST_GPT_KEY;

    @Override
    public Boolean executeOrder(String order) {
        FastgptVO answer = fastgpt.getAccess(order, FAST_GPT_KEY, false, false);
        //判断返回内容是否为json格式，如果不是，则重新请求一次
        if(JsonUtil.isNotJson(answer.getContent())){
            answer = fastgpt.getAccess(order, FAST_GPT_KEY, false, false);
            if(JsonUtil.isNotJson(answer.getContent())){
                log.error("指令返回结构错误，检查大模型返回内容: " + answer.getContent());
                return false;
            }
        }
        log.info("执行指令问答:" + order + "\n接口返回指令: \n" + answer.getContent() + "\n");
        JSONObject  rs = JSONObject.parseObject(answer.getContent());
        String type = rs.getString("type");
        Map<String, String> map = MapUtil.objectMapToStringMap(JsonUtil.jsonObjectToMap(rs.getJSONObject("data")));
        OrderModuleEnum module = OrderModuleEnum.fromValue(type);
        Boolean result = false;
        switch (module) {
            case ROV://ROV
                result = rovService.SetROVData(map);
                break;
            case WORK_CHAMBER://作业舱
                result = rovService.SetZYCData(map);
                break;
            case SUPPORT_MONITORING://保障监控
                result = rovService.SetBZJKData(map);
                break;
            case NAVIGATION://导航
                result = rovService.SetGUIDEData(map);
                break;
            case SALVAGE_BODY://打捞本体
                result = rovService.SetDLBTData(map);
                break;
            case MANIPULATOR://机械臂
                result = rovService.SetJXBData(map);
                break;
            case PERMISSION_SWITCH://权限切换
                result = rovService.SetQXQHData(map);
                break;
            case MODULARIZATION://模块化
                result = rovService.SetMKHData(map);
                break;
            case CABLE_LAYING://铺缆
                result = rovService.SetPLData(map);
                break;
            default:
                return false;
        }
        return result;
    }
}
